/*
 * @lc app=leetcode.cn id=374 lang=javascript
 *
 * [374] 猜数字大小
 */

// @lc code=start
/** 
 * Forward declaration of guess API.
 * @param {number} num   your guess
 * @return 	     -1 if num is higher than the picked number
 *			      1 if num is lower than the picked number
 *               otherwise return 0
 * var guess = function(num) {}
 */

/**
 * @param {number} n
 * @return {number}
 */
var guessNumber = function(n) {
    // 二分法逼近
    let left = 1
    let right = n
    let flag = 0
    while(!flag) {
        let middle = Math.floor((left + right) / 2)
        if (guess(middle) === 0) {
            flag = middle
        } else {
            if (guess(middle) > 0) {
                if (left === middle) {
                    left = middle + 1
                } else {
                    left = middle
                }
            } else {
                right = middle
            }
        }
    }
    return flag
};
// @lc code=end

